package com.p2p.front.util;

import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.multipart.commons.CommonsMultipartFile;


public class ImageZipUploadValidator {
	private static final Logger		log				= LoggerFactory.getLogger(ImageZipUploadValidator.class);

	public static final String		resourcePrefix	= "product";

	public static final String[]	resourcePostfix	= { "jpg", "html","png" };

	public static boolean validate(CommonsMultipartFile file,Model model){
		boolean flag = true;
		StringBuffer sb = new StringBuffer();
		try{
			ZipInputStream zipInputStream = new ZipInputStream(file.getInputStream());
			ZipEntry entry;
			// 判断文件结构和后缀名是否有效
			while ((entry = zipInputStream.getNextEntry()) != null){
				String entryName = entry.getName();
				log.debug("entry: {}", entryName);
				if (entry.isDirectory()){// 文件夹
					if (!entryName.startsWith(resourcePrefix) && !entryName.startsWith("__MACOSX")){
						flag = false;
						log.debug("invalidate entry: {}", entryName);
						sb.append("无效的资源文件：" + entryName + "<br>\n");
					}
				}else{
					if (!entryName.startsWith("__MACOSX") && !entryName.endsWith(resourcePostfix[0]) && !entryName.endsWith(resourcePostfix[1]) && !entryName.endsWith(resourcePostfix[2])){
						flag = false;
						log.debug("invalidate entry: {}", entryName);
						sb.append("无效的资源文件：" + entryName + "<br>\n");
					}
				}
			}
			model.addAttribute("message", sb.toString());
		}catch (IOException e){
			log.debug("Cann't create zipinputstream from {}", file.getName());
			model.addAttribute("message", "读取资源文件失败！" + e.getMessage());
			flag = false;
			e.printStackTrace();
		}
		return flag;
	}
}
